<?php

namespace addons\cms\controller\api;

use addons\cms\model\Archives as ArchivesModel;
use addons\cms\model\ArchivesInteraction;
use addons\cms\model\ScoreLog;
use addons\cms\model\SocietiesSign;
use addons\third\model\Third;
use app\admin\model\cms\ActivitySign;
use app\common\model\cms\Delivery;
use app\common\model\User;
use think\Cache;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 文档
 */
class Verification extends Base
{
    protected $noNeedLogin = ['index', 'detail', 'verification_info','get_channel','lists','comment_list'];

    public function verification_info()
    {

        $row = $this->request->post('', '', 'trim,xss_clean');

        $rule = [
            'code|编号' => 'require',
            'type|类型' => 'require|in:user,activity_sign,delivery',
        ];
        $msg = [
            'code.require' => 'The number cannot be empty',
            'type.require' => 'Please fill in the type',
            'type.in' => 'Type error',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($row);
        if (!$result) {
            $this->error($validate->getError());
        }

        if ($row['type'] == 'user'){
            $info = \addons\cms\model\User::where(['societies_no' => $row['code']])->field('id,nickname,username,mobile,score,mobile,is_societies,societies_no,avatar')->find();
            if (!$info){
                $this->error('Membership does not exist');
            }
            $info['societies'] = [];
            if ($info['is_societies'] == 1){
                $info['societies'] = SocietiesSign::where('user_id', $info['id'])->field('name,mobile,gender,user_address,email')->find();
            }
            $info['type'] = 'user';
            $this->success('',$info);
        }
        if ($row['type'] == 'activity_sign'){
            $info = ActivitySign::where('verification_code',$row['code'])->find();

            if (!$info){
                $this->error('Registration does not exist');
            }

            $activity = \addons\cms\model\Activity::where('status', 'normal')
                ->where('id',$info['activity_id'])->field('id,title,title_zh_cn,title_en,image,start_time,end_time,address,address_zh_cn,address_en,attend_num,status')->find();
            $lang = getHeaderLang();
            if ($lang == getDefaultLang()){
                $activity->title = $activity['title_zh_cn'];
            }
            $this->success('',[
                'sign_info' => $info,
                'activity_info' => $activity,
                'type' => 'activity_sign'
            ]);
        }
        if ($row['type'] == 'delivery'){
            $info = Delivery::where('qrcode_str',$row['code'])->find();

            if (!$info){
                $this->error('Shipping information does not exist');
            }
            $user_info = \addons\cms\model\User::where('id',$info['user_id'])->field('id,username,mobile,address,email,province,city,district')->find();
            if ($user_info->province && $user_info->city && $user_info->district){
                $lang = getHeaderLang();
                $field = 'id,pid,name';
                if ($lang != getDefaultLang()){
                    $field = 'id,pid,name_'.$lang.' as name';
                }
                $province_info = \app\common\model\cms\Area::where('id',$user_info['province'])->field($field)->find()['name'] ?? '';
                $city_info = \app\common\model\cms\Area::where('id',$user_info['city'])->field($field)->find()['name'] ?? '';
                $district_info = \app\common\model\cms\Area::where('id',$user_info['district'])->field($field)->find()['name'] ?? '';
                $user_info->address = $province_info.'-'.$city_info.'-'.$district_info.' '.$user_info['address'];
            }
            $this->success('Signature information',[
                'delivery' => $info,
                'user_info' => $user_info,
                'type' => 'delivery'
            ]);
        }
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 积分核销
     */
    public function score(){

        $row = $this->request->post('', '', 'trim,xss_clean');

        $rule = [
            'user_id|用户ID' => 'require',
            'score|积分' => 'require',
            'type|类型' => 'require|in:add,dec',
            'remark|备注' => 'require'
        ];

        $msg = [
            'user_id.require' => 'The user ID cannot be empty',
            'score.require' => 'Points cannot be empty',
            'type.require' => 'The type cannot be empty',
            'type.in' => 'Type error',
            'remark.require' => 'The note cannot be empty'
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($row);
        if (!$result) {
            $this->error($validate->getError());
        }

        $user_info = \addons\cms\model\User::where('id',$row['user_id'])->find();
        if (!$user_info){
            $this->error('The user does not exist');
        }

        if ($row['type'] == 'dec'){
            if ($user_info['score'] < $row['score']){
                $this->error('Insufficient points');
            }

        }
//        $count = ActivitySign::where(['user_id' => $this->auth->id,'activity_id' => $info->id])->count();
//        if ($count > 0){
//            $this->error('您已报名过该活动');
//        }

        $ver_id = $this->auth->id;
        Db::startTrans();
        try {
            if ($row['type'] == 'add'){
                $score = $row['score'];
            }else{
                $score = -$row['score'];
            }
            User::score($score,'verification', $row['user_id'],$ver_id,$row['remark']);

            $user_info = \addons\cms\model\User::where('id',$row['user_id'])->find();

            Db::commit();
            $this->success('',['score'=>$user_info->score]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('The operation failed');
        }

    }


    /**
     * @return void
     * @throws \think\exception\DbException
     * 核销积分日志
     */
    public function score_log()
    {
        $list = ScoreLog::where(['type' => 'verification','param_id'=> $this->auth->id])
            ->with(['user'=>function($query){
                $query->field('id,username,nickname,avatar,score');
            }])
            ->order('id DESC')
            ->paginate(10);

        $this->success('', $list->toArray());
    }


    public function activity_sign(){

        $activity_sign_id = $this->request->post('activity_sign_id', '', 'trim,xss_clean');
        if (!$activity_sign_id){
            $this->error('The parameter is incorrect');
        }

        $activity_sign = ActivitySign::where('id',$activity_sign_id)->find();

        if (!$activity_sign){
            $this->error('Registration does not exist');
        }

        if ($activity_sign->verification_status == 1){
            $this->error('Registration has been cancelled');
        }

        $ver_id = $this->auth->id;
        Db::startTrans();
        try {
            $data = [
                'verification_time' => time(),
                'verification_status' => 1,
                'verification_user_id' => $ver_id
            ];
            $user_name = User::where('id',$ver_id)->value('nickname');
            $data['verification_name'] = $user_name;
            ActivitySign::where('id',$activity_sign_id)->update($data);
            Db::commit();
            $this->success('The operation was successful');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('The operation failed');
        }

    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 签收发货
     */
    public function delivery(){

        $delivery_id = $this->request->post('delivery_id', '', 'trim,xss_clean');
        if (!$delivery_id){
            $this->error('参数错误');
        }

        $delivery_info = Delivery::where('id',$delivery_id)->find();

        if (!$delivery_info){
            $this->error('发货不存在');
        }

        if ($delivery_info->status == 1){
            $this->error('已签收，请问重复操作');
        }

        $ver_id = $this->auth->id;
        Db::startTrans();
        try {
            $user_name = User::where('id',$ver_id)->value('nickname');
            $data = [
                'verification_name' => $user_name,
                'verification_user_id' => $ver_id,
                'status' => 1,
                'finish_time' => time(),
            ];
            $delivery_info->save($data);

            Db::commit();
            $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }

    }

    /**
     * @return void
     * @throws \think\exception\DbException
     * 核销积分日志
     */
    public function activity_sign_log()
    {
        $list = ActivitySign::where(['verification_user_id'=> $this->auth->id])
            ->field('title,updatetime,deletetime,image',true)
//            ->with(['user'=>function($query){
//                $query->field('id,username,nickname,avatar,score');
//            }])
            ->order('id DESC')
            ->paginate(10);

        if ($list){
            foreach ($list as $k => $v){
                $v->activity = \addons\cms\model\Activity::where('id',$v->activity_id)->find();
//                $v->verification_time = date('Y/m/d H:i:s',$v->verification_time);
            }
        }
        $this->success('', $list);
    }

    /**
     * @return void
     * @throws \think\exception\DbException
     * 签收记录
     */
    public function delivery_log()
    {
        $list = Delivery::where(['verification_user_id'=> $this->auth->id])
            ->field('createtime,updatetime,qrcode,qrcode_str',true)
            ->order('id DESC')
            ->paginate(10);
        if ($list){
            foreach ($list as $k => $v){
                $user = User::where('id',$v->user_id)->find();
                $v->username = $user->nickname;
                $v->mobile = $user->mobile;
                $v->address = $user->address;
            }
        }
        $this->success('签收记录', $list);
    }
}
